package it.lefo.dateReminder;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import it.lefo.dateReminder.bo.ContactsRepository;
import it.lefo.dateReminder.helper.DbHelper;
import it.lefo.dateReminder.helper.Utilities;
import it.lefo.dateReminder.model.Contact;
import android.app.Activity;
import android.app.ListActivity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class EventsInDateView extends Activity{
	
	private ListView _lstEv;
	private TextView _txt1;
	private ArrayAdapter _myAdapter;
	SQLiteDatabase _db;
	ContactsRepository _cntRepo;
	List<Contact> _contacts = new ArrayList();
	SimpleAdapter _mSchedule = null;
	Date _dtSelected = null;
	     	
	@Override
    public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        setContentView(R.layout.eventlist);                
        
        _lstEv = (ListView)findViewById(R.id.eventsListView);
        _txt1 = (TextView)findViewById(R.id.txtEventList1);
        registerForContextMenu(_lstEv);

        //ListView Population
        DbHelper dbh = new DbHelper(this);          
		try {
			//db connection
			_db = dbh.getOrCreateDataBase();			
			_cntRepo = new ContactsRepository(_db);
	        
			//get params from bundle		
	        Bundle bundle = this.getIntent().getExtras();
	        if (bundle != null)
	        {
	        	if (bundle.containsKey("dateSelected")){
	        		_dtSelected = Utilities.StringToDate(bundle.getString("dateSelected"));
	        		_txt1.append(" " + Utilities.DateToString(_dtSelected, "dd/MM/yy"));
	        	}
			        
		        if (_contacts != null)
		        	_contacts = (List<Contact>) bundle.getSerializable("contacts");
		        else{
		        	// In this case the caller class is ReminderService
		        	Date dtToday = Calendar.getInstance().getTime();
		        	_contacts = _cntRepo.getAllBirthday(dtToday);
		        }	
	        }else{
	        	Date dtToday = Calendar.getInstance().getTime();
	        	_contacts = _cntRepo.getAllBirthday(dtToday);
	        }
	        
	        //ListView Population
	        ArrayList<HashMap<String, String>> listItem = new ArrayList<HashMap<String, String>>();
	        HashMap<String, String> map;
	        for (Contact contact : _contacts) {
				map = new HashMap<String, String>();
				map.put("r1", contact.getName().trim() + " " + contact.getSurname().trim());				
		        map.put("r2", Utilities.DateToString(contact.getBirthdate(),"dd/MM/yyyy"));
		        map.put("img", String.valueOf(R.drawable.contactimage));
		        map.put("id", contact.getId().toString());
		        listItem.add(map);
			}	        
	        _mSchedule = new SimpleAdapter (this.getBaseContext(), listItem, R.layout.eventlistitem,
	                new String[] {"img", "r1", "r2"}, new int[] {R.id.img, R.id.r1, R.id.r2});
	        _lstEv.setAdapter(_mSchedule);
	        
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}        
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0,R.string.EventsListView_insert,1,R.string.EventsListView_insert);
		menu.add(0,R.string.EventsListView_search,2,R.string.EventsListView_search);
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    if (item.getItemId() == R.string.EventsListView_insert){
	    	Intent i = new Intent(EventsInDateView.this,AddEventView.class);
			startActivity(i);
	        return true;
	    }
        else if (item.getItemId() == R.string.EventsListView_search)
	        return true;
        else
	        return super.onOptionsItemSelected(item);	    
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
	  super.onCreateContextMenu(menu, v, menuInfo);	  
	  menu.setHeaderTitle("Scegli l'operazione");
	  menu.add(0,v.getId(),0,R.string.EventsListView_delete);	  
	  menu.add(0,v.getId(),0,R.string.EventsListView_update);
	  menu.add(0,v.getId(),0,R.string.EventsListView_sendsms);
	}
		
	@Override
	public boolean onContextItemSelected(MenuItem item) {				
	  AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
	  HashMap<String, String> map = (HashMap<String, String>) _lstEv.getItemAtPosition(info.position);
	  Integer idContactSelected = Integer.parseInt(map.get("id"));
	  Contact contactSelected = _cntRepo.getContactById(idContactSelected);
	  if ("Modifica".equalsIgnoreCase((String)item.getTitle())) 
	  {
		  Bundle bundle = new Bundle();
		  bundle.putSerializable("contact", contactSelected);
		  Intent i = new Intent(EventsInDateView.this,UpdateEventView.class);
		  i.putExtras(bundle);	
		  startActivity(i);
		  return true;
	  }
	  else  if ("Elimina".equalsIgnoreCase((String)item.getTitle())) {
	    _cntRepo.delete(idContactSelected);
	    refresh();
	    return true;
	  }else  if ("Invia Sms".equalsIgnoreCase((String)item.getTitle())) {
		  Bundle bundle = new Bundle();
		  bundle.putSerializable("contact", contactSelected);
		  Intent i = new Intent(EventsInDateView.this,SmsView.class);
		  i.putExtras(bundle);	
		  startActivity(i);
		  return true;
	  }else
	    return super.onContextItemSelected(item);
    }
	
	private void refresh(){
	    if (_dtSelected != null){
	        _txt1.append(" " + Utilities.DateToString(_dtSelected, "dd/MM/yy"));
	        _contacts = _cntRepo.getAllContactsInDate(_dtSelected);	        
        }else{
        	_contacts = _cntRepo.getAllContacts();
        }
        
        //Set the adapter with the contacts
//        myAdapter = new ArrayAdapter<Contact>(this, android.R.layout.simple_list_item_1, contacts);	        
//        lstEv.setAdapter(myAdapter);
        
        ArrayList<HashMap<String, String>> listItem = new ArrayList<HashMap<String, String>>();
        HashMap<String, String> map;
        for (Contact contact : _contacts) {
			map = new HashMap<String, String>();
			map.put("r1", contact.getName().trim() + " " + contact.getSurname().trim());
	        map.put("r2", Utilities.DateToString(contact.getBirthdate(),"dd/MM/yyyy"));
	        map.put("img", String.valueOf(R.drawable.typeb_calendar_today));
	        map.put("id", contact.getId().toString());
	        listItem.add(map);
		}
        
        _mSchedule = new SimpleAdapter (this.getBaseContext(), listItem, R.layout.eventlistitem,
                new String[] {"img", "r1", "r2"}, new int[] {R.id.img, R.id.r1, R.id.r2});
        _lstEv.setAdapter(_mSchedule);
	}
	
}
